package com.example.seh.person;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.seh.MainActivity;
import com.example.seh.R;
import com.example.seh.UserDTO;
import com.example.seh.constant.Constant;
import com.example.seh.home.substitution.AddressInfoDTO;
import com.example.seh.home.substitution.DeliverDTO;
import com.example.seh.util.ImgUtil;
import com.example.seh.util.LoginActivity;
import com.example.seh.util.UserMsg;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PersonSettingActivity extends AppCompatActivity {
    private RelativeLayout avatarChoose;
    private CircleImageView avatar;
    private EditText name;
    private TextView account;
    private ListView lvAddress;
    private Button addAddress, submit, avatarSubmit, passwordExchange;
    private List<String> addressList = new ArrayList<>();
    private AddressAdapter adapter;
    private final int CHOOSE = 2;
    private File file = null;
    private Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Log.e("add",UserMsg.addressInfoDTOS.size() + "");
                    adapter.notifyDataSetChanged();
                    break;
                case 2:
                    List<String> addresses = new ArrayList<>();
                    for (int i = 0; i < UserMsg.addressInfoDTOS.size(); i++) {
                        addresses.add(UserMsg.addressInfoDTOS.get(i).getDistrict());
                    }
                    UserMsg.addresses.addAll(addresses);
                    Log.e("add","地址add");
//                    addressList.addAll(addresses);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_setting);
        getViews();
        setDatas();
        setListeners();
        getData();
        adapter = new AddressAdapter(getApplicationContext(), UserMsg.addresses, R.layout.person_setting_address_item);
        lvAddress.setAdapter(adapter);
    }

    private void setDatas() {
        try {
            if (!"".equals(UserMsg.userDTO.getPic())) {

//                avatar.setImageBitmap(ImgUtil.toRoundBitmap(ImgUtil.stringToBitmap(UserMsg.userDTO.getPic())));

                //avatar.setImageBitmap(ImgUtil.toRoundBitmap(ImgUtil.stringToBitmap(UserMsg.userDTO.getPic())));
                Glide.with(getApplicationContext())
                        .load(UserMsg.userDTO.getPic())
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(avatar);

            }
            name.setText(UserMsg.userDTO.getUsername());
            account.setText(UserMsg.userDTO.getPhone());
            Log.e("add", "获取地址");
            if (!Constant.isGetAddress) {
                getAddress();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getAddress() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.GETADDRESS + UserMsg.userDTO.getUserId())
                .build();
        Log.e("地址：", request.url().toString());
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("add", result);
                Gson gson = new Gson();

                Type type = new TypeToken<List<AddressInfoDTO>>(){}.getType();
                List<AddressInfoDTO> list = gson.fromJson(result,type);
                UserMsg.addressInfoDTOS = list;
                if (!Constant.isGetAddress) {
                    Message message = new Message();
                    message.what = 2;
                    handler.sendMessage(message);
                    Log.e("add","sendMsg");
                    Constant.isGetAddress = true;
                }

            }
        });
    }


    private List<String> getData() {
        List<String> list = new ArrayList<>();
//        list.add("诚朴园3号楼");
//        list.add("启智园四号楼");
//        if (Constant.isGetAddress && Constant.isInitAddress) {
        if (UserMsg.addresses != null) {
            list.addAll(UserMsg.addresses);
        }
//            Constant.isInitAddress = false;
//        }
        return list;
    }


    private void setListeners() {
        addAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PersonSettingActivity.this, AddressChooseActivity.class);
                startActivityForResult(intent, 100);
            }
        });
        lvAddress.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //定义AlertDialog.Builder对象，当长按列表项的时候弹出确认删除对话框
                AlertDialog.Builder builder=new AlertDialog.Builder(PersonSettingActivity.this);
                builder.setMessage("确定删除?");
                builder.setTitle("提示");

                //添加AlertDialog.Builder对象的setPositiveButton()方法
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.e("del","size:" + UserMsg.addressInfoDTOS.get(position));
                        if (UserMsg.addressInfoDTOS.get(position).getAddressId() != null) {
                            deleteAddress(UserMsg.addressInfoDTOS.get(position).getAddressId());
                        }
                        UserMsg.addresses.remove(position);
                        UserMsg.addressInfoDTOS.remove(position);
                        adapter.notifyDataSetChanged();

                        UserMsg.goodsBuyAddress.remove(position);
                        UserMsg.goodsBuyAddressInfo.remove(position);
                    }
                });

                //添加AlertDialog.Builder对象的setNegativeButton()方法
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                builder.create().show();
                return false;
            }
        });
        avatarChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent openCamera = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(openCamera, CHOOSE);
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!"".equals(name.getText().toString()) && UserMsg.addressInfoDTOS.size() != 0) {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    JSONObject object = new JSONObject();
                    Gson gson = new Gson();
                    try {
                        object.put("userId", UserMsg.userDTO.getUserId());
                        object.put("username", name.getText().toString());
                        object.put("addressInfoDTOList", UserMsg.addressInfoDTOS);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    MediaType type = MediaType.parse("application/json;charset=utf-8");
                    RequestBody body = null;
                    try {
                        JSONObject result = new JSONObject(gson.toJson(object));
                        String msg = result.getString("nameValuePairs");

                        body = RequestBody.create(type, msg);
                        Log.e("sendaddress", msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Request request = new Request.Builder()
                            .url(Constant.UPDATEUSER)
                            .post(body)
                            .build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("okhttp", "获取数据失败");
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String result = response.body().string();
                            if ("更新信息成功".equals(result)) {
                                UserMsg.userDTO.setUsername(name.getText().toString());
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "更新信息成功", Toast.LENGTH_SHORT).show();
                                    }
                                });
                                finish();
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "更新信息失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }

                        }
                    });
                } else {
                    Toast.makeText(getApplicationContext(), "昵称或地址信息不完整", Toast.LENGTH_SHORT).show();
                }

            }
        });

        avatarSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (file != null) {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM);
                    RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
                    requestBodyBuilder.addFormDataPart("userId", UserMsg.userDTO.getUserId() + "")
                            .addFormDataPart("file", file.getName(), requestBody);

                    RequestBody body = requestBodyBuilder.build();

                    Request request = new Request.Builder()
                            .url(Constant.SUBMITAVATAR)
                            .header("Content-Type", "multipart/form-data")
                            .post(body)
                            .build();

                    Log.e("avatar", file.getName());
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("avatar", "发送失败");
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String result = response.body().string();
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String data = jsonObject.getString("data");
                                Log.e("avatar","result:" + data);
                                UserMsg.userDTO.setPic(data);
                                if (data != null) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(getApplicationContext(), "上传成功", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Log.e("avatar",result);
                        }
                    });
                } else {
                    Toast.makeText(getApplicationContext(), "请先选择图片", Toast.LENGTH_SHORT).show();
                }

            }
        });

        passwordExchange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PersonSettingActivity.this, PasswordExchangeActivity.class);
                startActivity(intent);
            }
        });
    }

    private void deleteAddress(int id) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.DELETEADDRESS + id)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp", "获取数据失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if ("删除成功".equals(result)) {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    private void getViews() {
        avatar = findViewById(R.id.person_setting_avatar);
        avatarChoose = findViewById(R.id.person_setting_avatar_choose);
        name = findViewById(R.id.person_setting_name);
        account = findViewById(R.id.person_setting_account);
        lvAddress = findViewById(R.id.person_setting_address_list);
        addAddress = findViewById(R.id.person_setting_address_choose);
        submit = findViewById(R.id.person_setting_submit);
        avatarSubmit = findViewById(R.id.person_setting_avatar_submit);
        passwordExchange = findViewById(R.id.person_setting_password_update);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            if (!UserMsg.addresses.contains(data.getStringExtra("address"))) {
                UserMsg.addresses.add(data.getStringExtra("address"));
                UserMsg.goodsBuyAddress.add(data.getStringExtra("address"));

                AddressInfoDTO addressInfoDTO = new AddressInfoDTO();
                addressInfoDTO.setUserId(UserMsg.userDTO.getUserId());
                addressInfoDTO.setContactName(UserMsg.userDTO.getUsername());
                addressInfoDTO.setDistrict(data.getStringExtra("address"));
                UserMsg.addressInfoDTOS.add(addressInfoDTO);
                UserMsg.goodsBuyAddressInfo.add(addressInfoDTO);

                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            } else {
                Toast.makeText(getApplicationContext(), "已存在此地址", Toast.LENGTH_SHORT).show();
            }
        }
        switch (requestCode) {
            case CHOOSE:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri uri = data.getData();
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                        Log.i("msg","src:" + uri.toString());
                        file = ImgUtil.uriToFile(uri, getApplicationContext());
                        Log.e("avatar",file.toString());
                        //预览图片
                        avatar.setImageBitmap(ImgUtil.toRoundBitmap(bitmap));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }
}